<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button id="addUsers" type="primary" plain @click="handlAdd">添加用户</el-button>
    <el-table border :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 三级菜单的排版要通过栅格化的静态来进行 -->
          <el-row v-for="firstChildItem in scope.row.children" :key="firstChildItem.id">
            <el-col :span="4">
              <el-tag
                closable
                @close="handleClose(scope.row.id,firstChildItem.id, scope.row)"
              >{{firstChildItem.authName}}</el-tag>
              <i class="el-icon-arrow-right" v-if="firstChildItem.children.length>0"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="secondChildItem in firstChildItem.children" :key="secondChildItem.id">
                <el-col :span="5">
                  <el-tag
                    type="success"
                    closable
                    @close="handleClose(scope.row.id,secondChildItem.id, scope.row)"
                  >{{secondChildItem.authName}}</el-tag>
                  <i class="el-icon-arrow-right" v-if="secondChildItem.children.length>0"></i>
                </el-col>
                <el-col :span="19">
                  <el-tag
                    type="warning"
                    v-for="lastChildItem in secondChildItem.children"
                    :key="lastChildItem.id"
                    closable
                    @close="handleClose(scope.row.id,lastChildItem.id, scope.row)"
                  >{{lastChildItem.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-tag type="info" v-if="scope.row.children.length<=0">该角色未经授权，请前往授权</el-tag>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <!-- <el-table-column prop="id" label="#" width="94"></el-table-column> -->
      <el-table-column prop="roleName" label="角色名称" width="240"></el-table-column>
      <el-table-column prop="roleDesc" label="描述" width="240"></el-table-column>
      <el-table-column prop="more" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit"></el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
          <el-button size="mini" type="primary" icon="el-icon-check" @click="rightAdd(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加用户弹框 -->
    <div class="addusers">
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <el-form :model="addrow" :rules="fromRules" ref="addRef">
          <el-form-item label="角色名称" label-width="90px" prop="roleName">
            <el-input v-model="addrow.roleName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" label-width="90px" prop="roleDesc">
            <el-input v-model="addrow.roleDesc" type="text" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadUsers">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 编辑用户弹框 -->
    <div class="editusers">
      <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
        <el-form :model="editrow" :rules="fromRules">
          <el-form-item label="角色名称" label-width="90px" prop="roleName">
            <el-input v-model="editrow.roleName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" label-width="90px" prop="roleDesc">
            <el-input v-model="editrow.roleDesc" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editdialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadEdit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 权限树 -->
    <el-dialog title="大神树" :visible.sync="RightdialogTableVisible">
      <el-tree
        :data="data2"
        show-checkbox
        node-key="id"
        ref="tree"
        default-expand-all
        :default-checked-keys="selectIds"
        :props="defaultProps"
      ></el-tree>
      <el-button id="uploadRightBtn" type="primary" round @click="uploadTree">提交</el-button>
    </el-dialog>
  </div>
</template>
<script>
import { selectList, delUserRight, addUserRight, uploadUsersRight, delUserListRight, addRight, powerList } from '@/api'
export default {
  created () {
    this.initList()
  },
  data () {
    return {
      data2: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      tableData: [],
      // 节点树
      treeArr: [],
      dialogFormVisible: false,
      editdialogFormVisible: false,
      RightdialogTableVisible: false,
      //   添加部分数据
      addrow: {
        roleName: '',
        roleDesc: ''
      },
      roleId: '',
      //   编辑部分数据
      editrow: {
        roleName: '',
        roleDesc: ''
      },
      fromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ]
      },
      lastChildItemId: 0,
      selectIds: []
    }
  },
  methods: {
    initList () {
      selectList()
        .then(res => {
          console.log(res)
          this.tableData = res.data.data
        })
    },
    // 添加功能
    // 点击添加按钮
    handlAdd () {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // 清除校验信息需要调用form表单的clearValidate()方法
        this.addrow.roleName = ''
        this.addrow.roleDesc = ''
        this.$refs.addRef.clearValidate()
      })
    },
    // 添加
    uploadUsers () {
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addUserRight(this.addrow)
            .then(res => {
              console.log(res)
              if (res.data.meta.status === 201) {
                this.$message(res.data.meta.msg)
                this.initList()
                this.dialogFormVisible = false
                this.addrow.roleName = ''
                this.addrow.roleDesc = ''
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
        } else {
          this.$message.error('请输入正确的信息')
        }
      })
    },
    // 删除功能
    handleClose (roleId, rightId, row) {
      console.log(roleId, rightId, row)
      delUserRight(roleId, rightId, row)
        .then(res => {
          console.log(res)
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            // this.initList()
            // 重新刷新页面会导致次级菜单闭合，用户体验不好，因此通过删除请求的返回值来直接覆盖给整个表格
            row.children = res.data.data
          }
        })
    },
    // 编辑操作
    handleEdit (row) {
      console.log(row)
      this.editdialogFormVisible = true
      this.editrow.id = row.id
      this.editrow.roleName = row.roleName
      this.editrow.roleDesc = row.roleDesc
      console.log(this.editrow)
    },
    // 确认编辑
    uploadEdit () {
      uploadUsersRight(this.editrow)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.initList()
            this.editdialogFormVisible = false
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
    },
    // 删除操作
    handleDelete (row) {
      console.log(row)
      this.$confirm('确定要删除角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableData.length === 1 && this.total !== 1) {
          this.pagenum -= 1
        }
        // 点击确定执行的操作
        delUserListRight(row.id)
          .then(res => {
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg)
              this.initList()
            } else {
              this.$message.error(res.data.meta.msg)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取权限树
    rightAdd (row) {
      console.log(row)
      this.selectIds = []
      row.children.forEach(firstChildItem => {
        if (firstChildItem.children && firstChildItem.children.length > 0) {
          firstChildItem.children.forEach(secondChildItem => {
            if (secondChildItem.children && secondChildItem.children.length > 0) {
              secondChildItem.children.forEach(lastItem => {
                this.selectIds.push(lastItem.id)
              })
            }
          })
        }
      })
      this.RightdialogTableVisible = true
      this.roleId = row.id
      console.log(this.roleId)
      powerList('tree')
        .then(res => {
          if (res.data.meta.status === 200) {
            console.log(res)
            this.data2 = res.data.data
            this.$message.success(res.data.meta.msg)
            console.log(this.data2)
          }
        })
    },
    // 获取点击到的树节点
    getCheckedKeys () {
      console.log(this.$refs.tree.getCheckedKeys())
      // this.treeArr = this.$refs.tree.getCheckedKeys().toString()
      let allCheckedKeys = this.$refs.tree.getCheckedKeys()
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      this.treeArr = [...allCheckedKeys, ...halfCheckedKeys]
      // console.log(this.treeArr)
    },
    // 提交权限树
    uploadTree () {
      this.getCheckedKeys()
      addRight(this.roleId, this.treeArr.join(','))
        .then(res => {
          console.log(res)
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.initList()
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
      this.RightdialogTableVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.roles {
  #addUsers {
    margin-bottom: 10px;
  }
  .el-tag {
    margin: 5px 5px 5px 0;
  }
  #uploadRightBtn {
    margin-top: 20px;
    margin-left: 10px;
  }
}
</style>
